使用sed(或awk)删除最后一个char之前的4个字符

问题描述 投票:2回答:2

我想在最后一个字符之前删除4个字符。

输入:

abc2a982
e1kei9e5bc5
e1edeaww58476

预期产量:

abc2
e1kei95
e1edeaww6

到目前为止,我尝试过:

cat file | while read line; do echo $line | sed 's/.\{4}$\1/';done

我想应该有别的东西而不是\1

awk sed
2个回答
4
投票
% cat input | sed 's/....\(.\)$/\1/'
abc2
e1kei95
e1edeaww6

0
投票

如果你有冲动单独使用bash,并避免使用sed,你可以使用parameter expansion来操纵你的字符串。

while read -r line; do
  allbutlast1="${line%?}"          # strip the last character from $line
  lastchar="${line#$allbutlast1}"  # strip what we just captured from start of line
  allbutlast5="${line%?????}"      # strip the last 5 characters
  printf '%s%s\n' "$allbutlast5" "$lastchar"
done

或者如果你使用bash作为你的shell,你有additional options

while read -r line; do
  printf '%s%s\n' "${line:0:$(( ${#line} - 5))}" "${line:$(( ${#line} - 1 ))}"
done

(压缩bash代码以保存丢弃变量。)

POSIX代码(第一个示例)使用参数扩展${var%...}${var#...}来构造输出。 Bash代码使用${var:start:length}表示法,arithmetic expansion$(( ... ))

这个答案主要用于学术目的。使用awk或sed可以获得比使用shell脚本逐行处理输入更好的性能。

说到这个,awk解决方案可能会反映出bash解决方案:

awk '{print substr($0,1,length($0)-5) substr($0,length($0))}'

请注意,虽然bash的${var:start:length}表示法开始将字符编号为零,但awk的substr()函数从1开始。

© www.soinside.com 2019 - 2024. All rights reserved.