By default, the awk
split into a string using the white space character as a separator.
So if it’s done:
echo "20151223152832_alexsandro_felix.txt" | awk '{print $9}'
nothing will be returned, because there is no white space in the string and even if it had, it would take 8 spaces for the print at position 9 to return something.
Try changing the string now, including a blank space:
echo "20151223152832 _alexsandro_felix.txt" | awk '{print $1}'
Will be returned: 20151223152832
echo "20151223152832 _alexsandro_felix.txt" | awk '{print $2}'
Will be returned: _alexsandro_felix.txt
The command ls -lh
returns a string in this format:
-rw-rw-r-- 1 cantoni cantoni 0 Jan 12 10:39 20151223152832_alexsandro_felix.txt
So by making a awk '{print $9}'
the file name is printed. The danger of this approach is if the file name contains spaces. If this happens, then the awk '{print $9}'
will not return the whole file name.
Explained this, a way to solve this problem without using the awk
would be using the following command:
ls -A 20151*
In the context of the question problem would be this:
array=($(ls -A 20151*));
It is possible to change the separator by which the awk
split into a string, see example below:
echo "20151223152832:_alexsandro_felix.txt" | awk -F':' '{print $2}'
Will be returned: _alexsandro_felix.txt
In this case, the separator was the character ':'
your problem certainly lies in this line: ($(ls 20151* |awk '{ print $9 }')) Is there any way you can post some examples of file names starting with 20151*? Post the name of the whole file, including the extension, if any.
– cantoni
this is not the issue as all filenames are basically in this format: "20151223152832_alexsandro_felix.txt"
– asfelix
Check it out, I don’t know how this can be working running manual like you said, because when doing awk '{ print $9 }' in the file name 20151223152832_alexsandro_felix.txt really can’t return anything. It would only work this way if, for example, your string had 9 blank spaces in the file name. Then the awk would print the 9th position of that "vector".
– cantoni
Post what you want to return which then becomes easier to help. What should be the contents of the test.txt file based on this filename pattern you have?
– cantoni