質問

Hi I have an input file with entries. Each line starts with a hostname ( host1, host2). I need to create a file name after the hostname that will contain list of entries on each line after the colon. Can someone assist? Please see example below

input file

host1*stop*start : runit stopit gather 
host2*stop*start : unite cease cut chop eat

output file name host1

runit 
stopit 
gather 

output file name host2

unite 
cease 
cut 
chop 
eat
役に立ちましたか?

解決

awk '{n=split($1,array,"*"); for (i=3;i<=NF;i++) {print $i >array[1]}}' input

The above uses whitespace as a field separator. Consequently, for your first example line, the first field is host1*stop*start, the second is :, and the rest are: runit, stopit, gather. We first need to extract the hostname from the the first field. We do this by splitting that field on the character * which puts the hostname in the variable array[1]. Then, we write the third field and all thereafter as separate lines to the file named by array[1].

他のヒント

Using just builtins:

while IFS=: read -a ln; do
    printf "%s\n" ${ln[@]:1} > "${ln[0]%%\**}"
done < file.txt
  • Reads and splits each line on : into an array
  • The 0th element of the array will be e.g. "host1*stop*start". This is turned into the required filename by using a parameter expansion to delete every * and all following text
  • All remaining elements will be a space-separated list. This is passed to printf, which will format each member of that list according to its format specifier
  • The printf output is redirected to the filename generated above

Using perl:

perl -lane '$,="\n";$F[0]=~/([^*]+)/;open(O,">$1");print O @F[2..$#F];close(O)' file

With comments:

perl -lane '             # Split the line on space and load them in an array
    $,="\n";             # Set the output list separator to newline
    $F[0] =~ /([^*]+)/;  # Capture the file name from first array index
    open(O,">$1");       # Open a file handle with filename using captured group
    print O @F[2..$#F];  # print everything from 3rd index to end of line in that file
    close(O)             # Close the file handle
' file
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top