简体   繁体   中英

How can I keep specific characters from a line with sed commands?

I trying to print only specific charecters from a line, not necesserlly orderd and could appear more than once. I've searched for sed commands for it but found only ways to specify characters to delete and not to keep. thanks

For example:

For line "helloabcdabcdhello"
And desired characters: h,l
Output should be: hllhll

To print specific characters in a string, delete the complement of wanted characters, for example with tr :

$ echo this is a test | tr -c -d aieo
iiae$

Notice, that I didn't want the newline. With Bash:

$ foo="this is a test"
$ echo ${foo//[^aeio]/}
iiae

But please, post a proper sample with expected output. You'll attract a lot more enthusiasts and experts and get more and better quality answers.

Edit : Using your example with sed :

$ echo helloabcdabcdhello | sed 's/[^hl]//g'
hllhll

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