【问题标题】:Append index variable at the end of each line在每行末尾附加索引变量
【发布时间】:2014-06-21 15:42:40
【问题描述】:

我正在尝试在我拥有的文件的每一行末尾附加一个索引变量。但是我不想丢失 textFile 中的转义字符,因此无法再次回显到文件中。

这是我尝试过的:

while read p; do               
                tempCom+=$p
                tempCom+=$indexVar
                echo $tempCom >> otherFile.txt               
                tempCom=""
done < result.txt

我追求的是什么:

Read:
"asdasdasdasdasdasd\ asdasd/asda"
"qweqweqweqweqweqwe\ qweqwe/qweq"

Output:
"asdasdasdasdasdasd\ asdasd/asda" 1
"qweqweqweqweqweqwe\ qweqwe/qweq" 2

请注意,indexVar 是存储在其他地方的索引,不一定对应于它所附加到的行。

【问题讨论】:

  • 您能否展示一个 indexVar 文件的小样本?
  • @G-- 它只是一个被拉入变量的数字。

标签: bash shell sh


【解决方案1】:

您的问题很可能是引用问题。还要注意read 语句中的IFS=-r 选项。

while IFS= read -r p
    tempCom+=$p$indexVar
    printf '%s\n' "$tempCom" >> otherFile.txt # Observe the quotes
    tempCom=
done < result.txt

【讨论】:

    【解决方案2】:

    如果您只想将行号附加到末尾,为什么不使用awk

    awk '{print $0, "\t", NR}' < file.txt
    

    编辑 1:听起来您想使用 paste 然后(假设您只想逐行加入)

    paste file1.txt file2.txt > fileresults.txt
    

    编辑 2:您可以使用 sed 然后:

    sed "s|$|${indexVar}|" input
    

    【讨论】:

    • 对不起,我编辑了我应该已经说过的帖子,但索引与行号不对应。
    • 您的sed 解决方案适用于indexVar 在整个文件中永远不会更改并且不包含| 符号。
    • 我不太确定 indexVar 是如何设置/更改的。
    • Indexvar 可能会更改,因此 sed 选项不可行。 -r 标志做到了。谢谢。
    【解决方案3】:

    使用read 命令的-r 选项,以便保留反斜杠。

    while read -r p; do
    

    【讨论】:

    • @mixkat 你接受了这个答案,很好,但请确保你使用我的建议:使用IFS= 并引用tempCom 的扩展。
    • @gniourf_gniourf 注意!谢谢!
    猜你喜欢
    • 2013-04-16
    • 2021-09-01
    • 1970-01-01
    • 2018-09-17
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多