Reputation: 23
Need to duplicate the last word in machine pattern
hi abd 123
hiabd 2 44
hi 12 233
Output should be:
hi abd 123 123 123
hiabd 2 44 44 44
Here's what I tried:
sed '/abd/!d' F1
But it's not duplicating the last word. I know I can do something with backtracking but its misunderstood, please assist I can use only sed command.
Upvotes: 0
Views: 145
Reputation: 7499
For variety, using only bash
:
while IFS= read -r line; do
[[ $line =~ abd ]] && echo "$line ${line##* } ${line##* }"
done < file
You can choose a different character set as a word delimiter, for example:
#space and tab are delimiters
${line##*[[:blank:]]}
#character 'a' and 'c' are delimiters
${line##*[ac]}
Also, you don't even need the binary operator =~
. [[ $line = *abd* ]]
will suffice. Note that using bash
is noticeably slower than the awk
and sed
solutions here.
Upvotes: 0
Reputation: 133538
In case you need an awk
solution, following may also help you in same too.
awk '/abd/{print $0,$NF,$NF}' Input_file
Output will be as follows.
hi abd 123 123 123
hiabd 2 44 44 44
Upvotes: 1
Reputation: 88664
With GNU sed:
sed -n '/abd/ {s/\( [^ ]\+\)$/&\1\1/p}' file
or
sed -nE '/abd/{ s/( [^ ]+)$/&\1\1/p}' file
Output:
hi abd 123 123 123 hiabd 2 44 44 44
See: Back-references and Subexpressions
Upvotes: 0