我正在尝试将 cut 命令的输出用于 head 命令以输出特定行。我发现如果将数字输入 head 命令 10+,它就可以正常工作。所以我想知道 cut -c1-2 是否包括了导致 head 命令跳闸的单个数字的空格?
我的代码
#!/bin/bash
echo "Enter your name"
read input
cut -c5-19 filelist | grep -n "$input" | cut -c1-2 > cat
while read cat
do
head -$cat filelist | tail -1 > filelist2
done < cat
任何意见或建议将不胜感激!谢谢 :) 编辑
FULLRanjit Singh Marketing Eagles Dean Johnson
FULLKen Whillans Marketing Eagles Karen Thompson
PARTPeter RobertsonSales Golden TigersRich Gardener
CONTSandeep Jain President Wimps Ken Whillans
PARTJohn Thompson Operations Hawks Cher
CONTCher Operations Vegans Karen Patel
FULLJohn Jacobs Sales Hawks Davinder Singh
FULLDean Johnson Finance Vegans Sandeep Jain
PARTKaren Thompson EngineeringVegans John Thompson
FULLRich Gardener IT Golden TigersPeter Robertson
FULLKaren Patel IT Wimps Ranjit Singh
这是“文件列表” 我收到的错误是“head:无效的尾随选项 -- :” 如果我输入“Patel”作为名称,它会起作用。
最佳答案
修改问题的答案
替换:
cut -c5-19 filelist | grep -n "$input" | cut -c1-2 > cat
与:
cut -c5-19 filelist | grep -n "$input" | cut -d: -f1 >cat
grep -n
在行号和行文本之间放置一个冒号。因此,很自然地使用冒号作为 cut
的字段分隔符并要求 cut 返回第一个字段。
根据您展示的内容,脚本可以进一步简化为:
read -p "Enter your name: " input
linenum=$(cut -c5-19 filelist | grep -n "$input" | cut -d: -f1)
head -$linenum filelist | tail -1 > filelist2
原始问题的答案
由于您没有向我们展示 filelist
,我们只能猜测问题所在。如果您对包含空格的 filelist
是正确的,那么这就是解决方案。替换:
head -$cat filelist | tail -1 > filelist2
与:
head -${cat## } filelist | tail -1 > filelist2
构造 ${cat## }
从变量 cat
中删除所有前导空格。
关于bash - 剪切命令包含一个令人困惑的 head 命令的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26229079/