问题
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:
- number the lines
- turn each line into a sed command that searches for the given number of characters and removes the one following them
- run the generated sed command on the original file with the numbers removed
- 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