How do I append text to a file?
What is the easiest way to append text to a file in Linux?
I had a look at this question, but the accepted answer uses an additional program ( sed ) I’m sure there should be an easier way with echo or similar.
4 Answers 4
Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.
Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.
You could also use printf in the same way:
Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc :
Now when you try to do echo «hello» > file.txt you will get a warning saying cannot overwrite existing file .
To force writing to the file you must now use the special syntax:
You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:
How to add file extensions based on file type on Linux/Unix?
This is a question regarding Unix shell scripting (any shell), but any other «standard» scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
These files have different original file types such as png, zip, doc, pdf etc.
Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the file command?
Answer:
J.F. Sebastian’s script will work for both ouput of the filenames as well as the actual renaming.
5 Answers 5
Here’s mimetypes’ version:
Following @Phil H’s response that follows @csl’ response:
Here’s a snippet for old python’s versions (not tested):
It should work on Python 2.3.5 (I guess).
to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a list of MIME-types and example file extensions on the net.
Following csl’s response:
to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find list of MIME-types and suggested file extensions on the net.
I’d suggest you write a script that takes the output of file -i filename , and returns an extension (split on spaces, find the ‘/’, look up that term in a table file) in your language of choice — a few lines at most. Then you can do something like:
in bash, or throw that in a bash script. Or make the get_extension script bigger, but that makes it less useful next time you want the relevant extension.
Edit: change from for f in * to ls | while read f because the latter handles filenames with spaces in (a particular nightmare on Windows).
This post and this website contains affiliate links. See my disclosure about affiliate links.
how to add new files into an archive file (tar, gz, zip) in linux (also delete files)
There are several programs, both command line and GUI based that will allow you to view and extract the contents of an archive. But sometimes, you will need to modify an existing archive file, such as add files to archive, delete an existing file or renaming a file.
Most of the GUI applications, like Ark support adding and deleting files using the drag and drop. This is accomplished by extracting the archive in memory and performing the modification operation. The archive is then re-archived from memory and saved to the disk. A GUI interface may not always be available and you may want to modify the archive from command line without extracting it completely.
You always do have the option of extracting the archive to the hard disk first. You can then modify the contents and re-create the archive from the modified content. This requires space on the disk and extra time for extraction and archiving.
The archives are usually the combination of two different process: archiving and compression. There are a couple of caveats that you should be aware of while modifying the archives.
compressed archive: You can directly modify an archive but not a compressed archive. Modifying the compressed file without uncompressing it first will corrupt the file. For example, this means that you can modify a .tar file, but not a .tar.gz file. The .tar.gz should first be uncompressed to .tar.
file position: There is really no way to “replace” a file inside the archive while also maintaining its position. You can always extract the whole archive to a temp location, modify or replace the file and then archive it back up. But we are only dealing with the scenario of doing the operations in place without extracting the entire archive.
Add files to archive
tar archive
Assuming that you have a archive with .tar extension, you can use the -r (or –append) option of the tar command to add/append a new file to the end of the archive.
bash$ tar rvf /path/to/archive.tar /path/to/newfile.txt
You can use the -v option to have a verbose output to verify the operation. The other option that can be used with the tar command is -u (or –update).
The update refreshes the files that are newer than the ones in the archive, so it works slightly different than the –append (or -r) option but provides the same functionality for the addition of a new file.
bash$ tar uvf /path/to/archive.tar /path/to/newfile.txt
Another feature of the archive is that it allows for multiple files with the same name. If you append a file with the same name, then the file is just appended to the end of the archive without deleting the previous one. But when you extract the archive, it will extract the latest version (by its order inside the archive) of the file.
zip archive
The zip archive can be modified using the zip command. The -r option of the zip command allows you to adding files.
bash$ zip -rv zipfile.zip newfile.txt newfile1.txt
where the zipfile.zip is the name of an existing zip file and the newfile.txt is the file that you want to add to the zip archive.
jar archive
In case of the jar files, you can use the jar command. The –update (or -u) option allows you to add or update files into a jar archive.
bash$ jar -uvf jarfile.jar newfile.txt
Again, you can add multiple files in a single command just like the zip command.
Delete files from archive
tar archive
You can use the –delete option of the tar command to delete existing files from inside an archive.
bash$ tar -dvf archive.tar filename.txt
zip archive
You can use the –delete (or -d) option of the zip command to delete files from the archive. The zip command take multiple arguments for file names and supports regular expressions in the argument. This allows for deletion of multiple files with a single command.
bash$ zip -d zipfile.zip filename.doc \*.txt
The above command will delete the file named filename.doc and also all the files with an extension of .txt.
jar archive
Unfortunately there is no option with the jar command to delete the files. But jar files are essentially zip files with .jar extension, hence you can use the zip command to delete the files, just as you would to a zip file.
bash$ zip -d jarfile.jar file1.txt file2.txt
Renaming files inside the archive essentially amounts to deleting the existing file and adding the new file. This will also cause the file to lose its position inside the tar archives.
Команда file в Linux
Команда file — одна из самых полезных, поскольку позволяет узнать тип данных, которые на самом деле содержатся внутри документа. Если у вас есть какой-либо файл, взятый из ненадёжного источника, не поленитесь проверить его с помощью этой команды, прежде чем нажать кнопку Открыть. Возможно, такая предосторожность покажется лишней, но она оградит вас от «встречи» с нежелательным контентом.
В большинстве дистрибутивов Linux утилита file (работу которой и запускает одноимённая команда) входит в стандартный набор программного обеспечения.
Синтаксис и опции file
Синтаксис команды file достаточно простой. Записывать её в эмуляторе терминала или консоли следует так:
file опции название_документа
Что же касается опций, то их у этой команды несколько десятков. Мы рассмотрим лишь основные:
- -b, —brief — запрет на демонстрацию имен и адресов файлов в выводе команды;
- -i, —mime — определение MIME-типа документа по его заголовку;
- —mime-type, —mime-encoding — определение конкретного элемента MIME;
- -f, —files-from — анализ документов, адреса которых указаны в простом текстовом файле;
- -l, —list — список паттернов и их длина;
- -s, —special-files — предотвращение проблем, которые могут возникнуть при чтении утилитой специальных файлов;
- -P — анализ определенной части файла, которая обозначается различными параметрами;
- -r, —raw — отказ от вывода /ooo вместо непечатных символов;
- -z — анализ содержимого сжатых документов.
Для того, чтобы ознакомиться с полным списком опций, выполните в терминале команду:
Примеры использования file
Если вам нужно всего лишь посмотреть тип файла, использовать опции не обязательно. Достаточно прописать имя команды, а также название файла и путь к нему, при условии, что он находится не в корневой папке:
Случается, что нужно проверить не один, а несколько файлов. Чтобы не выполнять команду много раз подряд, перечисляйте названия всех файлов через пробел:
file /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff
Как видно на примере, картинки с расширениями gif и tiff в действительности оказались текстовыми документами, а архив с расширением zip — PDF документом. Кстати, команда file даёт возможность не только проверить, является ли архив архивом, но и заглянуть внутрь, чтобы узнать, что в нём содержится. Для этой цели используется опция -z:
file -z /home/main-user/losst/testarchive.zip
Как вы успели заметить, команда, возвращая ответ, постоянно выводит названия файлов, что в некоторых случаях бывает удобно, но зачастую только усложняет чтение результатов. Отключить эту функцию легко — воспользуйтесь опцией -b:
file -b /home/main-user/losst/test-file.gif /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file2.tiff
Иногда нужно узнать не просто тип файла, а его MIME-тип. В таком случае на помощь приходит опция -i:
file -i -b /home/main-user/losst/fileA.sbin /home/main-user/losst/fileG.aspx /home/main-user/losst/fileH.lua
Нередко по каким-либо причинам утилита не может найти указанный файл: например, вы ошиблись буквой в его названии или неверно указали папку, в которой он находится. Тогда вывод информации об этом файле предваряет фраза cannot open. Впрочем, есть возможность видоизменить результат, добавив в него сообщение об ошибке. Для этого используйте опцию -E.
Сравните вывод команды с опцией -E и без неё:
file -E -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif
file -b /home/main-user/losst/test-file1.zip /home/main-user/losst/test-file4.raw /home/main-user/losst/test-file.gif
Еще один способ работы с утилитой file — запись названий и адресов документов в простой текстовый файл. Применяя этот способ на практике, не забывайте добавлять к команде опцию —files-from, после которой указывайте имя файла, содержащего список документов, и путь к нему.
file —files-from /home/main-user/losst/list_of_files.txt
Выводы
Команда file помогает избежать ситуаций, когда вам приходится открывать подозрительные файлы, не будучи уверенными в их содержимом. Также вы можете использовать её для проверки содержимого нескольких архивов, если есть необходимость найти потерявшийся в большом массиве файлов документ, но нет желания просматривать все архивы вручную.