简体   繁体   中英

how to add 1 .txt 2.txt 3.txt 4.txt at the end of each line of file

a.txt

12
23
45
56

Expected output:

12 >1.txt
23 >2.txt
45 >3.txt
56 >4.txt

I have tried below-given this command but it's not working:

sed -i s/$/\>1.txt/ a.txt

I want to store the value 12 in the file 1.txt ; 23 in 2.txt ; 45 in 3.txt ; and 56 in 4.txt

I am using Busybox, so I don't have Bash, and non-portable uses of Awk etc will also probably not work.

您可以使用 awk 并为每一行增加一个 int

awk 'BEGIN{i=1} /.*/{printf "%s >%d.txt\n",$0,i; i++}' a.txt

Using sed

$ n=1; while read -r line; do sed s"/.*/echo & > $n.txt/e" <<< $line;n=$((n+1)); done < a.txt
$ cat 1.txt
12

This might work for you (GNU sed & expr):

sed -n 'x;s/.*/expr & + 1/e;x;/\S/G;s/\(.*\)\n\(.*\)/echo "\1" >\2.txt/e' file

Store a counter in the hold space and increment it for each line input.

Append the counter to the current line and then format an expression to store the current line in a file designated by the counter and evaluate it.

If your actual question is how to write each line to a new file, try

awk 'NR>1 { close(f) }
    { f=++n ".txt"; print >f }' a.txt

Demo: https://ideone.com/a65wFT (IdeOne runs on Linux but I have separately tested this on BusyBox v1.34.1 (2021-12-29 21:12:15 UTC))

If you can't get Awk to work, try

n=0
while read -r line; do
    echo "$line" >"$((++n)).txt"
done <a.txt

Perhaps see also split ; however, the Busybox split appears to have limited support for controlling the generated output file names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM