所以我有一个包含以下文本的文件:
puddle2_1557936:/home/rogers.williams/folderz/puddle2
我想使用 grep 命令
grep puddle2_1557936
与 cut 命令(或其他命令,如果需要)混合以仅显示这部分:
/home/rogers.williams/folderz/puddle2
到目前为止,我知道如果这样做
grep puddle2_1557936 | cut -d ":" -f1
然后就会显示
puddle2_1557936
那么有没有办法“反转”分隔符剪切命令?
注意:解决方案必须以
grep puddle2_15579636
开始。
您无需更改分隔符即可使用
cut
显示字符串的右侧部分。
-f
命令的cut
开关是由分隔符::
分隔的第n个元素,因此您只需键入:
grep puddle2_1557936 | cut -d ":" -f2
如果你想有趣,另一个解决方案(稍微调整一下):
使用grep:
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
或使用 sed:
sed -n 's/.*puddle2_1557936:\([^:]*\).*/\1/p' <<<'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
或使用 perl:
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
或使用ruby(感谢glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
或使用 awk:
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
或使用 python:
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
或仅使用bash:
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2