You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据文件行数批量生成并执行指定格式的Shell命令

Solution to Generate Commands Based on File Line Count

If your goal is to produce the final output (e.g., CREATE FROM (Maruti), CREATE FROM (Zen), etc.) instead of just printing the commands to run, the most efficient approach uses awk:

awk '{print "CREATE FROM (" $0 ")"}' output.txt

Why this works:

  • awk reads output.txt line by line in a single pass.
  • $0 represents the full content of the current line, so we don’t need to explicitly track line numbers.
  • For every line in the file, it outputs the formatted string with the line content wrapped in CREATE FROM ().

If you specifically need to generate the exact shell commands you listed (with sed -n np syntax), use a for loop combined with seq and wc -l:

First, capture the total number of lines in the file:

line_count=$(wc -l < output.txt)

Then loop through each line number and print the corresponding command:

for num in $(seq 1 "$line_count"); do
  echo "echo CREATE FROM (sed -n ${num}p output.txt)"
done

To execute these commands immediately (instead of just printing them), adjust the loop to run the actual logic:

for num in $(seq 1 "$line_count"); do
  echo "CREATE FROM ($(sed -n ${num}p output.txt))"
done

Quick Notes:

  • Using wc -l < output.txt avoids including the filename in the line count output, which keeps things clean.
  • The awk method is far more performant for large files—it reads the file once, whereas the sed loop reads the file once per line, which can slow down significantly with big datasets.

内容的提问来源于stack exchange,提问作者Hemanth Sai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:42:38