简体   繁体   中英

Replace the string which has a pattern like using sed

How to use like (.*) operation in sed to search a pattern (eg: STRING.*) and append "*" to the end of the string that matches.

Below is the example:

cat file1.txt 
MAC BOOK
MODERN MACHINE
MECHANICS
MOUNT
DISK
DATA INFORMATICS
cat file2.txt 
MAC
DATA
for line in $(cat file2.txt|uniq)
do
    sed -i "/$line.*/s/$line.*/$line.**/" file1.txt
done

Expected output:

cat file1.txt

MAC* BOOK
MODERN MACHINE*
MECHANICS
MOUNT
DISK
DATA* INFORMATICS

A one-liner:

$ sed -r '/'"$(paste -sd'|' file2.txt)"'/s/$/*/' file1.txt
MAC*
MACHINE*
MECHANICS
MOUNT
DISK
DATA*

The paste command creates a regular expression from file2:

$ paste -sd'|' file2.txt
MAC|DATA

Then the sed command looks file lines matching this regex, and replaces the end-of-line with an asterisk.

Add -i to the sed command to complete the task.


Update for your new input:

awk -v patt="$(paste -sd'|' file2.txt)" '{ 
    for (i=1; i<=NF; i++)
       if ($i ~ patt)
           $i = $i "*"
    print
}' file1.txt
MAC* BOOK
MODERN MACHINE*
MECHANICS
MOUNT
DISK
DATA* INFORMATICS

and to edit save the output back into the file:

tmp=$(mktemp)
awk ... file1.txt > "$tmp" && mv "$tmp" file1.txt

Or, with the latest GNU awk:

gawk -i inplace -v patt="$(paste -sd'|' file2.txt)" '{ 
    for (i=1; i<=NF; i++)
       if ($i ~ patt)
           $i = $i "*"
    print
}' file1.txt

You can just replace the "end of line" with * when you match like:

for line in $(uniq file2.txt); do
    sed -i "/$line/s/\$/*/" file1.txt
done

though this will only work with GNU sed, and it will match $line anywhere in the line, so hopefully that's what you expect

awk is better suited for this:

awk 'FNR==NR{a[$1];next} {for (i in a) if (index($1, i)) $0 = $0 "*"}1' file2.txt file1.txt
MAC*
MACHINE*
MECHANICS
MOUNT
DISK
DATA*

I think what you are looking for is this:

for line in $(cat file2.txt|uniq)
do
    sed -i "s/\(${line}.*\)/\1\*/" file1.txt
done

You can use () in the sed search to save the result and \\1 to use it in the replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM