簡體   English   中英

與cat和json2html結合使用for循環

[英]Combine for loop with cat and json2html

我嘗試將json文件轉換為html文件。 因此,我以后可以將它們導入網站。 我的想法是運行json2table創建一個表,然后將其寫入html目錄。 但是我不知道如何重定向json2table的輸出。

for file in $(ls json/*.json); do cat $file | json2table > html/$file.html; done

但是到此為止

bash: html/json/26.json.html: No such file or directory

是否有人可以幫助糾正錯誤? 謝謝

西爾維奧

您的${file}包含json目錄。 當您沒有目錄html/json ,重定向將失敗。
我認為您有一個subdir html ,可以從${file}刪除路徑:

for file in json/*.json; do 
   cat "${file}" | json2table > html/"${file#*/}".html
   # OR avoid cat with
   # json2table < "${file}" > html/"${file#*/}".html
done

作為獎勵,我刪除了ls ,添加了帶空格的文件名引號,並在注釋中顯示了如何避免使用cat

如果人們有相同的問題/項目或如何稱呼,我想提供所有完整的腳本。

第一個循環從JSON文件生成HTML表,並將其存儲在HTML文件中。 第二個循環將第一個循環的結果與模板結合在一起,以便您擁有完整的頁面。 在body標記中,只需搜索,刪除並用表格填充include。

#!/bin/bash

jdata="json"
hdata="html" 
template="tpl/tpl.html"
tmp="tmp"

# convert json to html
# https://stackoverflow.com/questions/51126226/combine-for-loop-with-cat-and-json2html/51126732#51126732

for file in $jdata/*.json;
do
    # php
    #php json.php $file > tmp/${file#*/}.html

    # ruby
    json2table < "${file}" > $hdata/"${file#*/}".html
done

# write html file 
# https://unix.stackexchange.com/questions/32908/how-to-insert-the-content-of-a-file-into-another-file-before-a-pattern-marker

for file in html/*.html;
do
    # extract Project Number for newfile 
    filename="$(basename -- "$file")"
    extension="${filename#*.}"
    filename="${filename%.*}"

    # save the project number
    NO="$(grep "No" $jdata/$filename | sed 's/[^0-9]*//g')"
    OUT="$NO.html"

    # write new html file
    sed 's/include/$x/g' tpl/tpl.html | x="$(<$file)" envsubst '$x' > html/$OUT

done

謝謝您的幫助和美好的一天Silvio

您的ls命令返回目錄以及文件名。

防爆。 json / 1.json json / 2.json json / 3.json

這樣:

for file in $(/bin/ls json/*.json)
do
    cat $file | json2table >html/$(basename $file).html
done
  • 在這種情況下,我總是使用ls的完整路徑,因為我想確保不使用任何可能已在其上定義的別名。
  • basename將目錄從$ file中刪除

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM