Shell 脚本剪切特定行和特定字段
Shell script cut the specific line and specific field
echo "./Desktop/data.txt"| cut -f 1 -d ":"
上面一行用分隔符“:”分割特定字段
但是如果我的文件包含多行,我如何用分隔符“:”来剪切特定的行和特定的字段?
如果您是根据行号选择行,那么您可以使用 sed。例如,对于第 10 行,执行:
cat "./Desktop/data.txt"| cut -f 1 -d ":" | sed -n 10p
- -n 告诉 sed 默认不打印行
- 10p 告诉 sed 当它到达第 10 行时,它应该打印。
如果您需要根据其中包含特定值的行来选择一行,那么我会使用 grep。如果该值与您要剪切的列在不同的列中,请务必在剪切之前进行 grep。
注意:原来的 post 说回声“./Desktop/data.txt”,我假设那应该是猫,而不是回声。
这是 AWK 的理想任务:
awk -F: 'NR == 2 {print }' "./Desktop/data.txt"
-F:
将字段分隔符设置为 :
NR == 2
是一个模式,意思是"record (line) number is equal to 2"
{print }
是对模式匹配执行的操作,意思是 "print second field"
我将用
模拟data.txt
文件
datatxt="Line 1 without colon
I want this:the part before the colon
nope, not me
other line with colon:that can be found"
您的命令显示所有行的第一个字段
echo "${datatxt}" | cut -f 1 -d ":"
Line 1 without colon
I want this
nope, not me
other line with colon
先用grep
可以得到:
的行:
echo "${datatxt}" | grep ":" | cut -f 1 -d ":"
I want this
other line with colon
您可以为一行输出附加 | head -1
。
这些指令也可以用 sed
完成。
使用 sed,您可以删除冒号后的所有内容:
echo "${datatxt}" | sed 's/:.*//'
Line 1 without colon
I want this
nope, not me
other line with colon
在 sed
中添加 grep 可以通过查找包含 /:/
.
的行来完成
您应该将其与 -n
和 p
.
结合使用
echo "${datatxt}" | sed -n '/:/ s/:.*//p'
I want this
other line with colon
当你想要一行输出时,可以使用
echo "${datatxt}" | sed -n '/:/ s/:.*//p' | sed -n '1p'
# OR SHORTER
echo "${datatxt}" | sed -n '/:/ {s/:.*//p;q}'
echo "./Desktop/data.txt"| cut -f 1 -d ":"
上面一行用分隔符“:”分割特定字段
但是如果我的文件包含多行,我如何用分隔符“:”来剪切特定的行和特定的字段?
如果您是根据行号选择行,那么您可以使用 sed。例如,对于第 10 行,执行:
cat "./Desktop/data.txt"| cut -f 1 -d ":" | sed -n 10p
- -n 告诉 sed 默认不打印行
- 10p 告诉 sed 当它到达第 10 行时,它应该打印。
如果您需要根据其中包含特定值的行来选择一行,那么我会使用 grep。如果该值与您要剪切的列在不同的列中,请务必在剪切之前进行 grep。
注意:原来的 post 说回声“./Desktop/data.txt”,我假设那应该是猫,而不是回声。
这是 AWK 的理想任务:
awk -F: 'NR == 2 {print }' "./Desktop/data.txt"
-F:
将字段分隔符设置为:
NR == 2
是一个模式,意思是"record (line) number is equal to 2"{print }
是对模式匹配执行的操作,意思是 "print second field"
我将用
模拟data.txt
文件
datatxt="Line 1 without colon
I want this:the part before the colon
nope, not me
other line with colon:that can be found"
您的命令显示所有行的第一个字段
echo "${datatxt}" | cut -f 1 -d ":"
Line 1 without colon
I want this
nope, not me
other line with colon
先用grep
可以得到:
的行:
echo "${datatxt}" | grep ":" | cut -f 1 -d ":"
I want this
other line with colon
您可以为一行输出附加 | head -1
。
这些指令也可以用 sed
完成。
使用 sed,您可以删除冒号后的所有内容:
echo "${datatxt}" | sed 's/:.*//'
Line 1 without colon
I want this
nope, not me
other line with colon
在 sed
中添加 grep 可以通过查找包含 /:/
.
的行来完成
您应该将其与 -n
和 p
.
echo "${datatxt}" | sed -n '/:/ s/:.*//p'
I want this
other line with colon
当你想要一行输出时,可以使用
echo "${datatxt}" | sed -n '/:/ s/:.*//p' | sed -n '1p'
# OR SHORTER
echo "${datatxt}" | sed -n '/:/ {s/:.*//p;q}'