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:
JavaScript
x
sed s/dog/cat/ >| tmp
or
sed s/dog/cat/ < tmp
Anyway lets say I had a file F1 and its contents was :
JavaScript
Hello hi 123
if a equals b
you
one abc two three four
dany uri four 123
The output should be:
JavaScript
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:
JavaScript
sed '/[^ ]*.[^ ]*.[^ ]*/s/[^ ]+/& & &/' F1
or
JavaScript
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
JavaScript
$ 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).