【问题标题】:Is there a program that functions like printf with an entire file as input?是否有一个程序可以像 printf 一样使用整个文件作为输入?
【发布时间】:2021-05-23 00:22:32
【问题描述】:

我的用例如下。

文件.txt

第一个参数:%s
第二个 %s 参数,
第三个 %s

运行prog file.txt "one" "$(ls dir1/dir2)" "three"

导致

第一个参数:一个
第二个文件 1 文件 2 文件 3 参数,
第三三

我最初考虑使用 sed,但是当 bash 替换被读取为像这样的格式字符时,这不可避免地会遇到问题 sed s/%1/$VAR/g -> sed s/%1/dir1/dir2/file1/g

我想我可以逐行迭代并在替换之前和之后获取文本,然后像这样插入

FIRST=$(sed "s/%s.*//" <<< $LINE)
SECND=$(sed "s/.*%s//" <<< $LINE)

echo "$FIRST $SUB $SECND"

虽然这仅限于每行一个子,但如果存在,我更喜欢更清洁的解决方案。

【问题讨论】:

    标签: linux bash shell sed printf


    【解决方案1】:

    请您尝试以下prog

    #!/bin/bash
    
    c=1                                     # counter for argv
    nl=$'\n'                                # newline character
    while IFS= read -r format; do           # read "file.txt" line by line
        (( c++ ))                           # increment the argv counter
        argv="${!c}"                        # obtain the argv indexed by "c"
        printf "${format}\n" "${argv//$nl/ }"
                                            # print the argv formatted by the line of "file.txt"
    done < "$1"                             # "$1" is assigned to "file.txt"
    

    替换 "${argv//$nl/ }" 只是将 ls 的输出中包含的换行符转换为空白字符。

    【讨论】:

      【解决方案2】:

      您可以将printf 与整个文件一起用作格式化字符串:

      printf "$(< file.txt)\n" one two three
      

      请注意,命令替换会删除尾随换行符,因此会添加一个单独的 \n;详情请见How to avoid bash command substitution to remove the newline character?

      【讨论】:

      • 不知道你可以用这种方式重定向文件。很有帮助。
      • @M_ 严格来说,相当于$(cat file.txt)(但更快)的$(&lt; file.txt)不是重定向。这是命令替换。
      猜你喜欢
      • 2021-10-18
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多