Как создать 100 файлов с именами a1, a2, a3, …. a100 в терминале?
Как создать 100 файлов с именами a1, a2, a3, …. a100 в терминале? Это вообще можно сделать в одну команду?
наибольшая «сложность» — получить последовательность чисел. дополнить же их буквами и передать программе touch — это просто.
стандартом posix, насколько мне известно, каких-либо «бортовых» средств, упрощающих процесс генерации, нет. можно воспользоваться каким-нибудь универсальным языком:
с помощью программы awk:
для создания файлов достаточно передать список программе touch:
с помощью программы bc:
для создания файлов достаточно передать список программе touch:
в операционной же системе gnu есть программа seq, как раз упрощающая генерацию:
для создания файлов достаточно передать список программе touch:
ну и современные «навороченные» оболочки типа bash/zsh понимают конструкцию <1..5>:
т.е. можно создать файлы опять-таки передав список программе touch:
How to create multiple files with the Terminal?
I’ve been learning to program with a really cool introductory book to C and I write off every example and task so I can learn the syntax by heart. I did every file manually until now, but the clicking, naming and saving gets exhausting.
I need a way to create multiple files like bspl0001.c , bspl0002.c , bspl0003.c , etc. and saving them in directory «learning_c» or something.
I’m a noob with Ubuntu / Linux and honestly only run it via VirtualBox because the IDE Geany was easy to set up. Thus, I don’t really know how the Terminal works.
edit I’ve just found myself in this old account of mine and am shaking my head about why I would ever want to learn a code syntax by heart. Funnily enough, I am almost done with my CS / Math BSc studies. Thanks much for the help in hindsight!
5 Answers 5
You can do this with these commands:
Explanation:
- This will create a folder called learning_c in the current folder
- The current folder usually is your home folder also called
- Yes, you can guess it, you’re entering on the newly created folder
- touch is a tool to create empty files and modify timestamps; we’re creating empty files.
- touch myfile will create an empty file called myfile .
The ugly code that follows ( bspl<0001..0003>.c ) is called a brace expansion. This is a great feature of the bash shell that allows you to create long lists of arbitrary string combinations. You can learn more about this in the Bash Hackers Wiki. In this case you will be making a long list of parameters that will be passed to touch . You can also use its long equivalent:
You can change the number of files: if you want 12 files, you can run bspl<0001..0012>.c .
You can use the following python code, you can modify it to fit your needs.
Save the following code with filename filecreator.py
And then execute it with this command:
Create correctly numbered (next) file with a shortcut key combination
Why create all files at once? The disadvantage is that you will have a lot of empty and unused files. What I am actually using: press a key combination to:
- have a script see in my code directory what should be the «next» file,
- create the correctly named file (including shebang) and
- open the new file in my editor (in my case Idle).
All in one keypress. That way you prevent a lot of (still) unused files; The files are only created if you need them.
A simplified version below (not running step 3). On every keypress, it will create a correctly numbered file like:
How to use
- Copy the script into an empty file
- In the head section, set the path to your directory (and optional: change the base name and/or extension, shebang).
- Save the script as create_empty.py
Run the script from a shortcut: System Settings > Keyboard > Custom Shortcuts. Add the command:
The bash way is good, but what if you are working with a shell that doesn’t support the curly brace expansion ? touch file <1..10>doesn’t work for me on mksh for instance. Here’s three alternative ways that work regardless of the shell.
A more shell-neutral approach would be to combine seq command to generate sequence of numbers formatted with printf options , and pass it to xargs command. For example,
Of course, Perl , being quite a widespred *nix tool, can do that as well. The specific one-liner command that we have here is the following:
Effectively what happens here is that we specify 3 command-line arguments: filename prefix, starting index, and ending index. Then we use do < >for $ARGV[1] .. $ARGV[2] to iterate for a specific range of numbers. Say, $ARGV[1] was 5 and $ARGV[2] was 9, we would iterate over 5,6,7,8 and 9.
What happens on each iteration within the curly braces ? we take each number specified with $_ , and using sprintf() function create a string m which splices up the prefix (first command-line argument, $ARGV[0] ) and the given number, but filling up the number with 4 zeros (which is done by printf -style of formatting , %04d part), and attach the .c suffix.As a result on each iteration we make up a name like bspl0001.c .
The open(my $fh, «>», $var);close($fh) effectively acts as touch command, creating a file with specified name.
While slightly lengthy it performs quite well, in fashion similar to Jacob Vlijm’s python script. It can also be converted to a script for readability if desired, like so:
Lets test this. First the one-liner:
And now the script:
Another approach would be with awk , running a for loop, redirecting to a specific file. The approach is similar to the perl one-liner with command-line arguments. While awk is primarily a text processing utility, it still can do some cool system programming.
Как с помощью touch создать несколько файлов в одной директории в терминале bash?
Есть директория app-search.
Мне нужно создать файлы app-search.js и app-search.scss внутри.
Я прописал команду touch app-search/
Но, создались 2 файла с фигурными скобками.
И возможно ли в терминале прописать команду, чтобы создать директорию и в ней нужные файлы?
- Вопрос задан более двух лет назад
- 2164 просмотра
Простой 2 комментария
- Вконтакте
Можно и так, например:
Ну и еще разными способами — например, список файлов в файле и пройтись циклом:
Поместить в статический файл (к примеру, /tmp/list) следующий текст:
Жизнь — это движение! А тестирование — это жизнь 🙂
Допустим, у нас есть некая папка test. Создадим в ней сотню директорий и кучу файликов в каждой:
Вот и все, дальше можно играться с ними!
- mkdir — создать директорию
- touch — создать файл (или изменить существующий, но если файла с таким именем нет, то команда создаст новый, пустой)
В книге, правда, команды были чуть сложнее:
Но на хабре мне подсказали, что можно и сократить!
Книга хорошая, очень рекомендую =)
1 комментарий:
полезная команда в копилку:
fallocate
Позволяет создать файл заданного размера. Например
fallocate -l 16K 16K.txt
создаст файл размером в 16 килобайт
Обо мне
Ольга Назина (Киселева) Уже более 12 лет как тестировщик 🙂
Автор портала Testbase — школы начинающих тестировщиков.
Автор Багреда — сервиса проверки названия багов
Я веду курсы для тестировщиков (для начинающих и не только). Отдельные ссылки смотри ниже в блоке «мои курсы»