简体   繁体   中英

How to use sed to replace string

I have a text file, it has the data format like below:

(1796208919349287,2592294224942165,1527446512828944,'abc','<a href=\'/users/7310739222965755\'>@xxd</a> Hello World!',
(2027149921324245,1612506768201878,2155431015165304,'def','<a href=\'/users/1696908528085920\'>@xyz</a> Would you like to.....?'
........

I am willing to remove <a href=\\'/users/7310739222965755\\'> and </a> from the text file. The data should be like this:

(1796208919349287,2592294224942165,1527446512828944,'abc','@xxd Hello World!',
(2027149921324245,1612506768201878,2155431015165304,'def','@xyz Would you like to.....?'
........

the command I tried was:

sed 's/<a href=\'\/users\/[[:digit:]]{16}\'\/'/ /g' file.sql

but it doesn't work.

please advise!

Thanks a lot!

In POSIX standard sed , you need to use \\{16\\} to enclose a count.

You also need to be extremely careful with single quotes. To embed a single quote 'in' a single-quoted string in the shell, you need to use the sequence:

'\''

The first of the quotes ends the current single quoted string; the backslash-quote embeds a single quote; and then last single quote resumes the single quoted string. You also need to be careful of the backslashes in the string; they are meaningful to sed (and to the shell).

This leads to:

sed -e 's/<a href=\\'\''\/users\/[[:digit:]]\{16\}\\'\''>/ /g' \
    -e 's/<\/a>/ /g' \
    file.sql

Warning: untested scripting.

You need to add more escaping for starters. Here's a working version:

sed -e "s/<a href\=\\\'\/users\/[[:digit:]]\{16\}\\\'>\([^<]*\)<\/a>/\1/g"

Also unless you have a particular reason to use sed I'd recommend perl as less escaping needed

cat test.txt | perl -pe "s/<a href=\\\'\/users\/\d{16}\\\'>([^<]*)<\/a>/\1/g"

This might work for you:

sed 's/<a href[^>]*>\([^<]*\)<\/a>/\1/' file
(1796208919349287,2592294224942165,1527446512828944,'abc','@xxd Hello World!',
(2027149921324245,1612506768201878,2155431015165304,'def','@xyz Would you like to.....\uff1f'
.......

如果要删除所有xml标记:

sed 's/<[^>]*>//g'

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