【问题标题】:Iterate through a file and parse in a bash script遍历文件并在 bash 脚本中解析
【发布时间】:2016-02-08 01:22:01
【问题描述】:

我有一个包含全名和用户名的文件,文件看起来像这样

Bob Smith bsmith
David Miller dmiller
...

我可以一次做一个:

useradd -c "Bob Smith" -d /home/bsmith -s /bin/bash bsmith

但我想弄清楚如何使用 while 循环遍历我的文件并使用变量来执行此操作。谢谢!

【问题讨论】:

标签: bash file while-loop


【解决方案1】:

你可以使用这样的东西

$ while read a b c; do echo -e "first: $a \t second: $b \t third: $c"; done << EOF
> Bob Smith bsmith
> David Miller dmiller
> EOF
first: Bob       second: Smith   third: bsmith
first: David     second: Miller          third: dmiller

【讨论】:

  • 使用read -r,除非您有特定的理由不这样做;没有它,反斜杠文字将从您的输入中删除。此外,任何未在其输出上打印-eecho -e 实现都不符合POSIX;使用printf 更安全。 (如:printf 'first: %s\tsecond: %s\t third: %s\n' "$a" "$b" "$c")。请参阅 POSIX 回显规范:pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html
  • 非常有帮助,谢谢。如何指定我正在阅读的文件?我可以使用 cmd line args 或者只是有一个绝对路径。为了澄清,循环中的名称将存储在变量 $a $b 和 $c?所以我的命令看起来像useradd -c "$a"+"$b" -d /home/"$c" -s /bin/bash "$c"
  • 正确。而不是&lt;&lt; EOF ... EOF 使用&lt; filename
  • useradd -c "$a $b";没有字符串连接运算符。相反,参数扩展允许您将值插入到字符串中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2018-10-03
  • 2013-04-18
  • 2021-11-11
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
相关资源
最近更新 更多