sed usage details

巴扎黑
巴扎黑Original
2017-06-23 14:34:011769browse

sed usage

1, replace symbols:

sed -e 's#/#-#g' -e's#:#-#g' passwd

2, use sed file input command:

vim 123.sed
s#:#/#g
s#/#-#g
sed -f 123.sed passwd

3, print:

sed -n 2p passwd

4 ,Replace the nth match:

sed 's/in/AAAAA/2' passwd
root:x:0:0:root:/root:/bin/bashbin:x:1:1:bAAAAA:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbAAAAA/nologin

Note: Only when in is matched for the second time in each line will it be replaced with AAAAA

5. Replace the mth match in the nth line:

sed '2s/in/AAAAA/2' passwd
root:x:0:0:root:/root:/bin/bashbin:x:1:1:bAAAAA:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologin

Note: You can use the -n -p combination

sed -n '2s/in/AAAAA/2p' passwd 
bin:x:1:1:bAAAAA:/bin:/sbin/nologin
sed -n '2,3s/in/AAAAA/2p' passwd
bin:x:1:1:bAAAAA:/bAAAAA:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbAAAAA/nologin
sed -n '2,$s/in/AAAAA/2p' passwd

Note: You can use $ to indicate the end

6 and save the replacement result to the file:

sed -n '2s/in/AAAAA/2pw passwd.sed' passwd 
bin:x:1:1:bAAAAA:/bin:/sbin/nologin
cat passwd.sed 
bin:x:1:1:bAAAAA:/bin:/sbin/nologin

7, back up the replacement result, and modify the source file:

sed -i.bak '2s/in/AAAAA/2' passwd
cat -n  passwd1	root:x:0:0:root:/root:/bin/bash2	bin:x:1:1:bAAAAA:/bin:/sbin/nologin
ls passwd*passwd  passwd.bak

8, conditional filter modification:

sed -n '/root/s/bin/AAAAA/p' passwd
root:x:0:0:root:/root:/AAAAA/bashoperator:x:11:0:operator:/root:/sAAAAA/nologin

9, sed multi-command execution:

sed  '1{s/root/ROOT/s/bin/BIN/
}' passwd
ROOT:x:0:0:root:/root:/BIN/bash
sed -n -e '1s/root/ROOT/' -e '1s/bin/BIN/' -e 1p passwd
ROOT:x:0:0:root:/root:/BIN/bash

The above is the detailed content of sed usage details. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn