仅在使用sed的情况下有4个单词时,将第一个单词与自身互换3次 [英] Swapping the first word with itself 3 times only if there are 4 words only using sed

查看:45
本文介绍了仅在使用sed的情况下有4个单词时,将第一个单词与自身互换3次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正尝试仅使用sed命令而不使用管道来解决问题.但是我可以将sed命令的结果传递给文件或从文件中读取.例如:

Hi I'm trying to solve a problem only using sed commands and without using pipeline. But I am allowed to pass the result of a sed command to a file or te read from a file. EX:

sed s/dog/cat/ >| tmp 
or
sed s/dog/cat/ < tmp

无论如何,我有一个文件F1,其内容为:

Anyway lets say I had a file F1 and its contents was :

Hello hi 123
if a equals b
you
one abc two three four
dany uri four 123

输出应为:

if if if a equals b
dany dany dany uri four 123

说明:该程序必须只打印正好有4个单词的行,并且在打印时必须将该行的第一个单词打印3次.

Explanation: the program must only print lines that have exactly 4 words and when it prints them it must print the first word of the line 3 times.

我尝试过执行以下命令:

I've tried doing commands like this:

sed '/[^ ]*.[^ ]*.[^ ]*/s/[^ ]\+/& & &/' F1

sed 's/[^ ]\+/& & &/' F1

但是我不知道怎么用sed计算一行中只有4个单词.任何帮助将不胜感激

but I can't figure out how i can calculate with sed that there are only 4 words in a line. any help will be appreciated

推荐答案

$ sed -En 's/^([^[:space:]]+)([[:space:]]+[^[:space:]]+){3}$/\1 \1 &/p' file
if if if a equals b
dany dany dany uri four 123

以上使用的sed支持带有 -E 选项的ERE,例如GNU和OSX sed).

The above uses a sed that supports EREs with a -E option, e.g. GNU and OSX seds).

这篇关于仅在使用sed的情况下有4个单词时,将第一个单词与自身互换3次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆