代码之家  ›  专栏  ›  技术社区  ›  mor3dr3ad

脚本可用于文件输入,但不能用于标准输入

  •  1
  • mor3dr3ad  · 技术社区  · 6 年前

    这真让我难堪。以下是我想做的:

    我试着把一篇文章从 newsboat 写剧本。这个脚本应该从文章中提取标题和Url。

    下面是一篇示例文章:

    Feed: NYT > Home Page
    Title: Hit Pause on Brett Kavanaugh
    Author: THE EDITORIAL BOARD
    Link: https://www.nytimes.com/2018/09/26/opinion/kavanaugh-supreme-court-hearing-delay.html?partner=rss&emc=rss
    Date: Thu, 27 Sep 2018 01:58:11 +0200
    
    The integrity of the Supreme Court is at stake.
    

    这篇文章通过新闻船的一个宏进行了传播:

    macro R pipe-to "cat | ~/.scripts/newsboat_extract"  
    

    以下是工作脚本:

    #!/bin/bash
    
    cat > ~/newsboat         #I do not really need this file, so if I can cut out saving to a file, I would prefer to
    
    title="$(awk -F: '/^Title:/{for(i=2;i<=NF;++i)print $i}' ~/newsboat)"
    url="$(awk -F: '/^Link:/{print $2 ":" $3}' ~/newsboat)"
    printf '%s\n' "$title" "$url" >> newsboat_result
    

    Hit Pause on Brett Kavanaugh
    https://www.nytimes.com/2018/09/26/opinion/kavanaugh-supreme-court-hearing-delay.html?partner=rss&emc=rss
    

    我想避免保存到文件。然而,无论出于什么原因,保存到一个变量都不起作用:这是一个不起作用的脚本!

    #!/bin/bash
    
    article=$(cat)
    
    title="$(awk -F: '/^Title:/{for(i=2;i<=NF;++i)print $i}' "$article")"
    url="$(awk -F: '/^Link:/{print $2 ":" $3}' "$article")"
    printf '%s\n' "$title" "$url" >> newsboat_result
    

    输出变成:

    #empty line
    #empty line
    

    有什么想法吗?-我对bash脚本和awk还很陌生,所以非常感谢大家对如何更有效地解决这个问题的评论。

    """""""""""" “解决方案” """"""""""""

    成功了,谢谢!

    #!/bin/bash
    
    article=$(cat "${1:--}")
    
    title="$(awk -F: '/^Title:/{for(i=2;i<=NF;++i)print $i}' <<< "$article")"
    url="$(awk -F: '/^Link:/{print $2 ":" $3}' <<< "$article")"
    printf '%s\n' "$title" "$url" >> newsboat_result
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   xhienne    6 年前

    在你的剧本里,你假设 $ARTICLE 是一个普通文件,您正在对它执行多个操作。首先,你阅读它与猫和存储的内容 ~/newsboat

    这不能与标准输入一起工作;只能读一次。

    #!/bin/bash
    
    article=$1
    feed_copy=~/newsboat
    cat "${article:--}" > "$feed_copy"     # Use stdin if parameter is not provided
    
    title="$(awk -F: '/^Title:/ { for(i=2; i<=NF; ++i) print $i }' "$feed_copy")"
    url="$(awk -F: '/^Link:/ { print $2 ":" $3 }' "$feed_copy")"
    
    printf '%s\n' "$title" "$url" >> "$feed_copy"
    

    • 为环境变量保留大写变量名(这只是一个惯例)
    • 你应该经常引用你的变量( cat "$article" ,不是 cat $article
    • 避免 echo ,使用 printf

    这个脚本还有其他的改进,但是很抱歉,我没有时间。


    [编辑]因为你实际上不需要 ~/新闻船 文件,这里是一个更新版本,遵循查尔斯·达菲的建议:

    #!/bin/bash
    
    feed_copy=$(cat "${1:--}")
    title="$(awk -F: '/^Title:/ { for(i=2; i<=NF; ++i) print $i }' <<< "$feed_copy")"
    url="$(awk -F: '/^Link:/ {print $2 ":" $3}' <<< "$feed_copy")"
    printf '%s\n' "$title" "$url"