Elio Messina
Elio Messina

Reputation: 111

Linux AWK - custom filename while split a file

awk '/{start}/{filename=NR".split"}; {print > filename}' alltickets.txt

This command split the file alltickets.txt in several files each time that find {start}.

right now the files produced are NR(number of the row).split.

1.split 5.split 6.split

I have a variable, let's say VAR='xxx' And I want that this variable is contained in the file name

to obtain:

1.xxx.split 2.xxx.split 3.xxx.split

After that if possible i would like to write these files in a specific directory.

Can you help me?

I've tried several options but every time I got an error.

You can propose also other solutions than awk.

Upvotes: 0

Views: 932

Answers (2)

Ed Morton
Ed Morton

Reputation: 203219

awk -v dir='/path/to/files' -v var="$VAR" '
    /{start}/{close(filename); filename=dir "/" NR "." var ".split"}
    {print > filename}
' alltickets.txt`

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133438

try following once and let me know if this helps you.

awk -v var="value_of_variable" '/{start}/{filename=NR "." var ".split";}; {print > filename}'   Input_file

Use -v var="$shell_variable" in case your variable has shell variable's value.

Upvotes: 1

Related Questions