0

我在使用 cut 命令时遇到问题,

这是原始文件的示例:

userid1:john doe smith:group1
userid2:jane doe smith:group2
userid3:paul rudd :group2

预期结果:

userid1
userid2
userid3

测试命令:

#!/bin/bash
clear
id=`id -u`
if [ $id -eq 0 ]

for i in `cat users.txt`
do
userid=`echo $i|cut -d":" -f1`

echo "$userid" >>temp.txt
`chmod 777 temp.txt`
done

这给了我这个输出:

userid1
doe
smith
userid2
doe
smith
userid3
rudd

如果我删除姓名和姓氏之间的空格,它会起作用,并且我指定“:”作为分隔符,不知道我错过了什么。

我怎样才能得到预期的结果?

干杯。

更新:修复了将 for 循环更改为 while...read 的问题。

4

1 回答 1

2

问题在于您的 bash 脚本。

 for i in `cat users.txt`

上面的行将您的文本按空格分开。做就是了:

cut -d":" -f1 < users.txt >>temp.txt
chmod 777 temp.txt

如果由于某种原因您 bash 单独处理每一行(可能是因为您需要对用户 ID 做一些事情而不仅仅是输出它),您可以使用read如下:

while read i 
do
userid=`echo $i|cut -d":" -f1`

echo "$userid" >>temp.txt
chmod 777 temp.txt
done < users.txt
于 2020-05-23T15:37:38.007 回答