如何根据文件行数批量生成并执行指定格式的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:
awkreadsoutput.txtline by line in a single pass.$0represents 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.txtavoids including the filename in the line count output, which keeps things clean. - The
awkmethod is far more performant for large files—it reads the file once, whereas thesedloop reads the file once per line, which can slow down significantly with big datasets.
内容的提问来源于stack exchange,提问作者Hemanth Sai
相关产品推荐
相关产品推荐

