How do I cut letter X out of a word?

好久不见. 提交于 2019-12-02 20:33:30

问题


I need to cut letter X out of a word: For example: I need to cut the first letter out of Star Wars, the fourth out of munich,...

1 star wars
4 munich
5 casino royale
7 the fast and the furious
52 a fish called wanda

to

tar wars
munch
casio royale
the fat and the furious
a fish called wanda

I already tried it with cut, but it didn't work. This was my command: sed 's/^\([0-9]*\) \(.*\)/ echo \2 | cut -c \1/'

So it gave me this output:

 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

And than if I send it to bash. I only get the X th letter of the word.

I need to do the exercise with sed and other commands. But I can't use awk or perl.

Thanks


回答1:


This might work for you (GNU sed):

sed 's/^\([0-9]*\) \(.*\)/echo '\''\2'\''|sed '\''s\/.\/\/\1'\''/e' file

This uses the e flag of the s command to evaluate the RHS and runs a second sed invocation using the backreferences from the LHS. Perhaps easier on the eye is this:

sed -r 's/^([0-9]*) (.*)/echo "\2"|sed "s#.##\1"/e' file



回答2:


You can use just bash and its parameter expansion:

while read n s ; do
    echo "${s:0:n-1}${s:n}"
done < input.txt

If you need one line, just remove the newlines and add a semicolon:

while read n s ; do echo "${s:0:n-1}${s:n}" ; done < input.txt

If you really need to use sed and cut, it's also doable, but a bit less readable:

cat -n input.txt \
| sed 's/\t\([0-9]\+\).*/s=\\(.\\{\1\\}\\).=\\1=/' \
| sed -f- <(sed 's/[0-9]*//' input.txt) \
| cut -c2-

Explanation:

  1. number the lines
  2. turn each line into a sed command that searches for the given number of characters and removes the one following them
  3. run the generated sed command on the original file with the numbers removed
  4. remove the extra leading space



回答3:


you can use sed in this way:

sed -e '1s/\([a-z]\)\{1\}//' -e 's/^[0-9]\+\s\+\(.*\)/\1/g' file.txt

The first sed regular expresion works on the first line and replace the first character and the second regular expresion works with rest of text, 1 column: one number or more, 2 column; one space or more, after this I put the remaining test in one match \(.*\) and replaced all with this match.



来源:https://stackoverflow.com/questions/34591564/how-do-i-cut-letter-x-out-of-a-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!