AvihuH
AvihuH

Reputation: 23

How to print specific pattern with sed

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

Answers (3)

PesaThe
PesaThe

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

RavinderSingh13
RavinderSingh13

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

Cyrus
Cyrus

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

Related Questions