我需要从一个单词中删除字母X: 例如:我需要从星球大战中删除第一个字母,这是慕尼黑的第四个字母,......
1 star wars
4 munich
5 casino royale
7 the fast and the furious
52 a fish called wanda
到
tar wars
munch
casio royale
the fat and the furious
a fish called wanda
我已经尝试过切割,但它没有用。
这是我的命令:
sed 's/^\([0-9]*\) \(.*\)/ echo \2 | cut -c \1/'
所以它给了我这个输出:
echo star wars | cut -c 5
echo munich | cut -c 5
echo casino royale | cut -c 5
echo the fast and the furious | cut -c 5
echo a fish called wanda | cut -c 52
而不是将它发送给bash。我只得到这个词的第X个字母。
我需要使用sed和其他命令进行练习。但我不能使用awk或perl。
谢谢
答案 0 :(得分:3)
你可以只使用bash及其参数扩展:
while read n s ; do
echo "${s:0:n-1}${s:n}"
done < input.txt
如果您需要一行,只需删除换行符并添加分号:
while read n s ; do echo "${s:0:n-1}${s:n}" ; done < input.txt
如果你真的需要使用sed
和cut
,它也可行,但可读性稍差:
cat -n input.txt \
| sed 's/\t\([0-9]\+\).*/s=\\(.\\{\1\\}\\).=\\1=/' \
| sed -f- <(sed 's/[0-9]*//' input.txt) \
| cut -c2-
说明:
答案 1 :(得分:1)
您可以这样使用sed
:
sed -e '1s/\([a-z]\)\{1\}//' -e 's/^[0-9]\+\s\+\(.*\)/\1/g' file.txt
第一个sed
正则表达式在第一行上起作用并替换第一个字符,第二个常规表达式与其余文本一起使用,1列:一个数字或更多,2列;一个或多个空格,在此之后我将剩余的测试放在一个匹配\(.*\)
中并用这个匹配替换所有。
答案 2 :(得分:1)
这可能适合你(GNU sed):
sed 's/^\([0-9]*\) \(.*\)/echo '\''\2'\''|sed '\''s\/.\/\/\1'\''/e' file
这使用e
命令的s
标志来评估RHS,并使用LHS的反向引用运行第二个sed调用。这可能更容易:
sed -r 's/^([0-9]*) (.*)/echo "\2"|sed "s#.##\1"/e' file