Skip to content
Advertisement

Swapping the first word with itself 3 times only if there are 4 words only using 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

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

The output should be:

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

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

or

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

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

Advertisement

Answer

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

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement