Bash + sed/awk/cut删除第n个字符

use*_*980 3 bash awk sed

我试图删除每行6,7和8个字符.

以下是包含文本格式的文件.

实际输出..

#cat test 
18:40:12,172.16.70.217,UP
18:42:15,172.16.70.218,DOWN
Run Code Online (Sandbox Code Playgroud)

格式化之后,期待下面.

#cat test
18:40,172.16.70.217,UP
18:42,172.16.70.218,DOWN
Run Code Online (Sandbox Code Playgroud)

即使我尝试过以下,也没有运气

#awk -F ":" '{print $1":"$2","$3}' test
18:40,12,172.16.70.217,UP

#sed 's/^\(.\{7\}\).\(.*\)/\1\2/' test  { Here I can remove only one character }
18:40:1,172.16.70.217,UP
Run Code Online (Sandbox Code Playgroud)

即使削减也失败了

#cut -d ":" -f1,2,3 test
18:40:12,172.16.70.217,UP
Run Code Online (Sandbox Code Playgroud)

需要删除每一行中的字符,如第6,7,8

建议请

Tom*_*ech 6

使用GNU cut,您可以使用--complement开关删除字符6到8:

cut --complement -c6-8 file
Run Code Online (Sandbox Code Playgroud)

否则,您可以自己选择其余字符:

cut -c1-5,9- file
Run Code Online (Sandbox Code Playgroud)

即字符1到5,然后9到每行的结尾.

使用awk你可以使用子串:

awk '{ print substr($0, 1, 5) substr($0, 9) }' file
Run Code Online (Sandbox Code Playgroud)

或者您可以编写正则表达式,但结果会更复杂.

例如,要从第一个以逗号分隔的字段中删除最后三个字符:

awk -F, -v OFS=, '{ sub(/...$/, "", $1) } 1' file
Run Code Online (Sandbox Code Playgroud)

或者,将sed与捕获组一起使用:

sed -E 's/(.{5}).{3}/\1/' file
Run Code Online (Sandbox Code Playgroud)

捕获前5个字符并在替换中使用它们,然后删除下3个字符.